package dao;// 申报信息数据访问对象
import model.Application;
import model.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ApplicationDAO {
    public boolean createApplication(Application application) {
        String sql = "INSERT INTO applications (applicant_id, content) VALUES (?, ?)";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, application.getApplicant().getId());
            pstmt.setString(2, application.getContent());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<Application> getApplicationsByStatus(int status) {
        List<Application> applications = new ArrayList<>();
        String sql = "SELECT a.id, a.content, u.id as applicant_id, u.username, u.password FROM applications a " +
                "JOIN users u ON a.applicant_id = u.id WHERE a.status = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, status);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String content = rs.getString("content");
                int applicantId = rs.getInt("applicant_id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                User applicant = new User(applicantId, username, password);
                Application application = new Application(id, applicant, content, status);
                applications.add(application);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return applications;
    }

    public boolean updateApplicationStatus(int applicationId, int newStatus) {
        String sql = "UPDATE applications SET status = ? WHERE id = ?";
        try (Connection conn = DBConnection.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, newStatus);
            pstmt.setInt(2, applicationId);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}    